<template>
  <div class="mt20">
    <el-tabs type="border-card">
      <el-tab-pane label="手游">
        <el-card class="box-card mt20" :body-style="{ padding: '18px 0px 5px', boxSizing: 'border-box' }">
          <el-row class="title">
            <el-col :lg="2" class="tac module-title ml20">
              <el-select v-model="queryServerInfo.game_id" @change="searchWyServer(1)" filterable>
                <el-option v-for="item in gameOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-col>
            <el-col :lg="2" class="tac module-title ml20">
              <el-popover
                placement="top-start"
                title="匹配规则提示！"
                width="250"
                trigger="hover"
                close-delay="0"
                popper-class="color-gray6"
                content="  区服区间用英文“-”表示，区服多选用英文“,”表示，例如：12-14,17 表示选择12,13,14,17服"
              >
                <el-input
                  slot="reference"
                  placeholder="请输入区服匹配规则"
                  clearable
                  v-model="queryServerStr"
                  @change="searchWyServer(2)"
                  style="width: 160px"
                ></el-input>
              </el-popover>
            </el-col>
            <el-col :lg="2" class="tac module-title ml20">
              <el-select multiple v-model="queryServer" @change="searchWyServer(3)" filterable placeholder="请选择游戏区服">
                <el-option v-for="item in serverOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-col>
            <el-col :lg="2" class="tac module-title ml20">
              <el-select v-model="queryServerInfo.status" @change="searchWyServer" filterable placeholder="请选择区服状态">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-col>
            <el-col :lg="5" class="tac module-title ml20" style="width: 344px">
              <el-date-picker
                v-model="queryTime"
                @change="searchWyServer"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-col>

            <el-col :lg="1" class="tal module-title ml20">
              <el-button plain type="primary" @click="reset">重置</el-button>
              <!-- <el-button plain type="primary" @click="search">查询</el-button> -->
            </el-col>
            <el-col :lg="7" class="tar module-title">
              <el-button plain type="primary" @click="addServer">添加服务器</el-button>
              <el-upload
                class="upload-demo ml10 mr10"
                action="invalid"
                :limit="1"
                style="width: 120px; display: inline"
                :http-request="uploadFile"
                :show-file-list="false"
                :file-list="fileList"
              >
                <el-button plain type="primary">导入服务器</el-button>
              </el-upload>
              <el-button plain type="primary" @click="downloadExcel(false)" :loading="downloadLoading1">导出当前页</el-button>
              <el-button plain type="primary" @click="downloadExcel(true)" :loading="downloadLoading2">导出所有页</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData" :height="tableHeight" v-loading="tableLoading">
            <el-table-column label="序号" type="index"> </el-table-column>
            <el-table-column prop="game_name" label="游戏名称"> </el-table-column>
            <el-table-column prop="serial_num" label="最近开服区号"> </el-table-column>
            <el-table-column prop="open_time" label="最近开服时间">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.open_time | formatTime }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="odpayRate" label="操作">
              <template slot-scope="scope">
                <el-button @click="editServer(scope.row, 'tab')">编辑</el-button>
                <el-button @click="manageServer(scope.row)">管理</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="tac"
            @size-change="handleSizeChange($event, 'pagination')"
            @current-change="handleCurrentChange($event, 'pagination')"
            :current-page.sync="pagination.currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pagination.perPages"
            layout="sizes, prev, pager, next"
            :total="pagination.total"
          >
          </el-pagination>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="页游"></el-tab-pane>
    </el-tabs>
    <!-- 编辑 -->
    <el-dialog
      :modal-append-to-body="false"
      :top="userAgent ? '60px' : '6vh'"
      :title="editFlag ? '编辑服务器' : '添加服务器'"
      :visible.sync="editServerFlag"
      width="1200px"
      @close="closeDialog"
    >
      <div class="wid-100 pt20 pb20">
        <el-form class="wid-100" inline label-position="right" label-width="140px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="游戏：">
                <el-select v-model="newServer.game_id" filterable style="width: 240px">
                  <el-option v-for="item in gameOptions2" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="序列号（对外）：">
                <el-input placeholder="请输入序列号（对外）" v-model.trim="newServer.serial_num" style="width: 240px"></el-input>
              </el-form-item>
              <el-form-item label="服务器名称：">
                <el-input placeholder="请输入服务器名称" v-model.trim="newServer.server_name" style="width: 240px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务器状态：">
                <el-select v-model="newServer.status" filterable style="width: 240px">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="开服时间：">
                <el-date-picker v-model="newServer.open_time" type="datetime" placeholder="选择日期时间" style="width: 240px"> </el-date-picker>
              </el-form-item>
              <el-form-item label="游戏研发服务器ID：">
                <el-input placeholder="请输入游戏研发服务器ID" v-model.trim="newServer.gc_server_id" style="width: 240px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="passCancel">取 消</el-button>
        <el-button type="primary" @click="passConfirm" size="small" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 管理界面 -->
    <el-dialog title="管理服务器" :visible.sync="serverManageVisble" width="80%">
      <el-table :data="serverManageData">
        <el-table-column property="game_name" label="游戏名称" width="120"></el-table-column>
        <el-table-column property="id" label="服务器id" width="80"></el-table-column>
        <el-table-column property="server_name" label="服务器名称" width="120"></el-table-column>
        <el-table-column property="net" label="线路" width="120"></el-table-column>
        <el-table-column property="open_time" label="开服时间">
          <template slot-scope="scope">
            <div>
              {{ scope.row.open_time | formatTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column property="status" label="状态">
          <template slot-scope="scope">
            <div>
              {{ scope.row.status | formatStatus(that) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column property="is_visible" label="是否可见">
          <template slot-scope="scope">
            <div>
              <i :class="scope.row.is_visible ? 'el-icon-check' : 'el-icon-close'"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="is_update" label="更新状态">
          <template slot-scope="scope">
            <div>
              <i :class="scope.row.is_update ? 'el-icon-check' : 'el-icon-close'"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="odpayRate" label="操作">
          <template slot-scope="scope">
            <el-button @click="editServer(scope.row, 'mag')">编辑</el-button>
            <el-button @click="deleteServer(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="tac"
        @size-change="handleSizeChange($event, 'pagination2')"
        @current-change="handleCurrentChange($event, 'pagination2')"
        :current-page.sync="pagination2.currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination2.perPages"
        layout="sizes, prev, pager, next"
        :total="pagination2.total"
      >
      </el-pagination>
    </el-dialog>
  </div>
</template>
<script>
// 复制
export default {
  data() {
    return {
      that: this,
      flag: false,
      btnLoading: false,
      tableLoading: false,
      downloadLoading1: false,
      downloadLoading2: false,
      gameOptions: [{ value: '', label: '所有游戏(all)' }], // 所有游戏
      gameOptions2: [], // 游戏列表去掉所有游戏
      serverOptions: [], // 区服列表
      queryServerStr: '',
      statusOptions: [
        { value: '', label: '所有状态' },
        { value: '-1', label: '未通过' },
        { value: '0', label: '待审核' },
        { value: '1', label: '正常' },
        { value: '2', label: '审核通过' },
        { value: '3', label: '关闭' },
      ],
      ref_arr: ['未通过', '待审核', '正常', '审核通过', '关闭'],
      // 所有游戏类型
      tableData: [], // 数据
      editFlag: false, // 编辑/添加
      manageFlag: false, // 管理
      editServerFlag: false, // 编辑/添加 弹窗
      // dialog
      // 分页
      pagination: {
        total: 0, // 表格数据条数
        pages: 0, // 总页数
        perPages: 10, // 每页的数量
        currentPage: 1, // 当前页
      },
      pagination2: {
        total: 0, // 表格数据条数
        pages: 0, // 总页数
        perPages: 10, // 每页的数量
        currentPage: 1, // 当前页
      },
      // 查询
      queryServerInfo: {
        game_id: '', // 游戏id
        serial_num: '', // 区服数
        status: '', // 开服状态
        open_time__gte: '', // 开始日期
        open_time__lte: '', // 结束日期
        page: 1, // 第一页默认第一(非必填)
        per_page: 10, // 每页数量默认10(非必填)
      },
      queryServer: [],
      queryServerInfo2: {
        game_id: '', // 游戏id
        serial_num: '', // 区服数
        status: '', // 开服状态
        open_time__gte: '', // 开始日期
        open_time__lte: '', // 结束日期
        page: 1, // 第一页默认第一(非必填)
        per_page: 10, // 每页数量默认10(非必填)
      },
      queryTime: [],
      // 新建 添加服务器字段
      newServer: {
        game_id: '',
      },
      closeFlag: false, // 编辑框关闭
      // 分类
      total_category: [],
      // 上传
      fileList: [],
      // 管理界面
      serverManageVisble: false,
      serverManageData: [],
    };
  },
  computed: {},
  created() {
    this.getServerListState();
    this.getWyGameList();
    this.getCurrentScreen();
  },
  mounted() {},
  methods: {
    search() {
      this.getServerListState();
    },
    // 查询
    searchWyServer(num = 0) {
      if (num > 1 && !this.queryServerInfo.game_id && !this.queryServerInfo2.game_id) {
        this.$message.warning('请先选择游戏，不然查询不到啊哥');
        return;
      }
      if (num == 2) {
        this.queryServerInfo.serial_num = this.disposeQueryServer(); // 输入框多选
      } else {
        this.queryServerInfo.serial_num = this.queryServer.join(','); // 下拉框多选
      }
      this.queryServerInfo.page = 1;
      this.queryServerInfo.open_time__gte = this.queryTime && this.queryTime.length > 0 ? this.toDate(this.queryTime[0]) : '';
      this.queryServerInfo.open_time__lte = this.queryTime && this.queryTime.length > 0 ? this.toDate(this.queryTime[1]) : '';
      if (num == 1) {
        this.queryServerInfo.serial_num = '';
        this.$api.checkGameServerList({ game_id: this.queryServerInfo.game_id }).then(res => {
          if (res.code == 0 || res.code == 200) {
            this.serverOptions = [...res.data];
            this.serverOptions.map(item => {
              item.value = item.serial_num;
              item.label = item.master_serial_num ? `${item.server_name}服-已合入${item.master_serial_num}服` : `${item.server_name}服`;
            });
          }
        });
      }
      this.getServerListState(this.queryServerInfo);
    },
    disposeQueryServer() {
      if (this.queryServerStr.indexOf(',') == -1 && this.queryServerStr.indexOf('-') == -1) {
        return this.queryServerStr;
      }
      let reg1 = /(\d+)-(\d+)/g;
      let reg2 = /(\d+),(\d+)/g;
      let tempArr1 = this.queryServerStr.match(reg1);
      let tempArr2 = this.queryServerStr.match(reg2);
      let arr = [];
      let queryArr = [];
      if (tempArr1 && tempArr1.length > 0) {
        // 取数组一中的数组
        tempArr1.forEach(item => {
          let start = item.split('-')[0] * 1;
          let end = item.split('-')[1] * 1;
          for (let i = 0; i <= end - start; i++) {
            arr.push(start + i);
          }
        });
      }
      if (tempArr2 && tempArr2.length > 0) {
        // 取数组二中的数组
        tempArr2.forEach(item => {
          arr.push(item.split(',')[0] * 1, item.split(',')[1] * 1);
        });
      }
      // 去重
      let newAr = [...new Set(arr)];
      // 搜取对用的server_id
      newAr.map(item => {
        let res = this.serverOptions.find(v => {
          return v.serial_num == item;
        });
        if (res) {
          queryArr.push(res.serial_num);
        }
      });
      return queryArr.join(',');
    },
    // 每页数量变化
    handleSizeChange(val, target) {
      if (target == 'pagination') {
        this.queryServerInfo.per_page = val;
        this.getServerListState(this.queryServerInfo);
      } else {
        this.queryServerInfo2.per_page = val;
        this.manageServer(this.queryServerInfo2);
      }
    },
    // 当前页
    handleCurrentChange(val, target) {
      if (target == 'pagination') {
        this.queryServerInfo.page = val;
        this.getServerListState(this.queryServerInfo);
      } else {
        this.queryServerInfo2.page = val;
        this.manageServer(this.queryServerInfo2);
      }
    },
    // 获取游戏列表信息
    getServerListState(params) {
      return new Promise(resolve => {
        this.tableLoading = true;
        let queryObj = params || this.queryServerInfo;
        this.$api.getServerList(queryObj).then(res => {
          this.tableLoading = false;
          if (res.code == 0 || res.code == 200) {
            this.tableData = res.items;
            this.pagination.currentPage = res.page;
            this.pagination.pages = res.pages;
            this.pagination.total = res.total;
            this.pagination.perPages = res.per_page;
            resolve(res.items);
          }
        });
      });
    },
    // 获取游戏列表下拉框信息
    getWyGameList() {
      // 1、获取游戏名+ 简称
      this.$api.getWyGameSelectList().then(res => {
        if (res.code == 0 || res.code == 200) {
          let list = res.data.map((item, index) => {
            return {
              value: item.id,
              label: `${item.name} - ${item.interface_name}`,
            };
          });
          this.gameOptions = [...this.gameOptions, ...list];
          this.gameOptions2 = [...list];
        }
      });
      // 2、获取游戏状态、游戏类型等下拉框选项
    },
    // 新建 / 编辑 通过
    passConfirm() {
      // 1、检查该输入的都输入了没
      if (this.checkInputInfo()) return;
      this.btnLoading = true;
      if (!this.editFlag) {
        // 新建
        this.$api.addServer(this.newServer).then(res => {
          this.btnLoading = false;
          if (res.code == 0 || res.code == 200) {
            this.$message.success('新建服务器成功！');
            this.editServerFlag = false;
            this.closeFlag = true;
            this.$store.commit('changeDialogFlag', true);
            this.getServerListState();
          }
        });
      } else {
        // 编辑
        if (isNaN(Number(this.newServer.status))) {
          let index = this.ref_arr.findIndex(item => {
            return item == this.newServer.status;
          });
          this.newServer.status = index - 1 + '';
        }
        this.$api.editServer(this.newServer).then(res => {
          this.btnLoading = false;
          if (res.code == 0 || res.code == 200) {
            this.$message.success('编辑成功！');
            this.editServerFlag = false;
            this.$store.commit('changeDialogFlag', true);
          }
        });
      }
    },
    passCancel() {
      this.editServerFlag = false;
    },
    // 检查输入的内容有没有完整
    checkInputInfo() {
      if (!this.newServer.game_id) {
        this.$message.warning('请选择游戏名称');
        return true;
      }
      if (!this.newServer.serial_num) {
        this.$message.warning('请输入序列号（对外）');
        return true;
      }
      if (!this.newServer.status) {
        this.$message.warning('请选择服务器状态');
        return true;
      }
      if (!this.newServer.open_time) {
        this.$message.warning('请选择开服时间');
        return true;
      }
      if (!this.newServer.server_name) {
        this.$message.warning('请输入服务器名称');
        return true;
      }
      if (!this.newServer.gc_server_id) {
        this.$message.warning('请输入游戏研发服务器ID');
        return true;
      }
      return false;
    },
    // 编辑服务器
    editServer(r, flag) {
      if (flag == 'tab') {
        this.manageFlag = false;
      } else {
        this.manageFlag = true;
      }
      this.editFlag = true;
      this.editServerFlag = true;
      this.newServer = r;
      this.newServer.status = this.ref_arr[this.newServer.status + 1];
      this.$store.commit('changeDialogFlag', false);
    },
    // 添加服务器
    addServer() {
      this.editFlag = false;
      this.editServerFlag = true;
      this.manageFlag = false;
      this.newServer = {};
      this.$store.commit('changeDialogFlag', false);
    },
    deleteServer(r) {
      this.$api.deleteOpenServer({ id: r.id }).then(res => {
        if (res.code == 200 || res.code == 0) {
          this.$message.success('删除成功！');
        }
      });
    },
    manageServer(r) {
      this.serverManageVisble = true;
      this.manageFlag = true;
      this.queryServerInfo2.game_id = r.game_id;
      this.getManageServerList(this.queryServerInfo2);
    },
    getManageServerList(obj) {
      this.$api.getServerList(obj).then(res => {
        if (res.code === 200) {
          this.serverManageData = res.items;
          this.pagination2.currentPage = res.page;
          this.pagination2.pages = res.pages;
          this.pagination2.total = res.total;
          this.pagination2.perPages = res.per_page;
        }
      });
    },
    // 自定义上传事件
    uploadFile(e) {
      let formFile = new FormData();
      let imgName = 'file';
      formFile.append(imgName, e.file);
      this.$api
        .importServer(formFile)
        .then(res => {
          if (res.code == 0 || res.code == 200) {
            this.$message.success('上传成功');
            this.fileList = [];
            this.getServerListState();
          }
        })
        .catch(err => {});
    },
    // 重置
    reset() {
      this.queryTime = [];
      this.serverOptions = [];
      this.queryServerInfo.game_id = '';
      this.queryServerInfo.serial_num = '';
      this.queryServerInfo.status = '';
      this.queryServerInfo.open_time__gte = '';
      this.queryServerInfo.open_time__lte = '';
      this.queryServerInfo.page = 1;
      this.queryServerInfo.per_page = 10;
      this.pagination.currentPage = 1;
      this.pagination.perPages = 10;
      this.getServerListState(this.queryServerInfo);
    },
    closeDialog() {
      this.$store.commit('changeDialogFlag', true);
      if (this.manageFlag) {
        this.getManageServerList(this.queryServerInfo2);
        return;
      }
      if (this.editFlag && !this.manageFlag) {
        this.getServerListState();
      }
    },
    // 下载excel
    async downloadExcel(flage) {
      let excel = '<table>';
      //设置表头
      let list;
      if (!flage) {
        // 当前页
        this.downloadLoading1 = true;
        list = this.tableData;
      } else {
        // 所有页
        this.downloadLoading2 = true;
        this.queryServerInfo.page = 1;
        this.queryServerInfo.per_page = 9999;
        list = await this.getServerListState(this.queryServerInfo);
      }
      let row = '<tr>' + '<td>序号</td>' + '<td>游戏名称</td>' + '<td>最近开服区号</td>' + '<td>最近开服时间</td>' + '</tr>';
      //换行
      excel += row;
      let l = list.map((o, i) => {
        return `<tr>
                  <td>${i + 1}</td>
                  <td>${o.game_name}</td>
                  <td>${o.serial_num}</td>
                  <td>${o.open_time ? o.open_time.replace(/T/, ' - ') : ''}</td>
        </tr>`;
      });

      excel += l.join('');
      excel += '</table>';
      //利用时间起文件名称
      var date = new Date();
      var fileName = '服务器列表' + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + '号' + date.getHours() + '点' + date.getMinutes() + '分';
      this.tableToExcel(excel, fileName);
      this.downloadLoading1 = false;
      this.downloadLoading2 = false;
      this.reset();
    },
  },
  components: {},
  filters: {
    formatTime(v) {
      return v.replace(/T/, ' - ');
    },
    formatStatus(v, that) {
      return that.ref_arr[v + 1];
    },
  },
};
</script>
<style lang='stylus' scoped>
body {
}

.el-dialog__body {
  padding: 10px 20px 30px !important;
}
</style>
